import { useState, ReactText, useEffect, useRef } from 'react';
import ProCard from '@ant-design/pro-card';
import { Avatar, Input, message, Modal, Tooltip } from 'antd';
import type { ProFieldFCMode } from '@ant-design/pro-utils';
import { api } from '@/global';
import ProDescriptions from '@ant-design/pro-descriptions';

import { request, Access, useAccess } from 'umi';
import ProForm, {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadDragger,
} from '@ant-design/pro-form';
import { fn } from 'moment';
import { PlusOutlined } from '@ant-design/icons';
type propsType = {
  selectedRowKeys: ReactText[];
};

type fileType = {
  fileName: string;
  id: string;
};

type moduleType = {
  id: string;
  fileName: string;
  fileSuffix: string;
  createTime: string;
  fileDescribe: string;
  fileOssPath: string;
  userName: string;
  storageName: string;
  deptName: string;
};

type deptTyp = {
  id: string;
  deptName: string;
};

const ModuleAddFileInfo = (props: any) => {
  const [fileInfo, SetFileInfo] = useState();

  return (
    <ModalForm<moduleType>
      title="新增文件"
      trigger={
        <a>
          <PlusOutlined />
          新增文件
        </a>
      }
      autoFocusFirstInput
      modalProps={{
        onCancel: () => console.log('run'),
      }}
      onFinish={async (values: moduleType) => {
        if (!fileInfo) {
          message.error('请选择文件');
          return;
        }

        const formData = new FormData();
        formData.append('storageName', values.storageName);
        formData.append('fileDescribe', values.fileDescribe);
        formData.append('fileName', values.fileName);
        formData.append('userName', values.userName);
        formData.append('file', fileInfo);

        const result = await request(api.insertStorageFileInfo, {
          method: 'post',
          data: formData,
        });

        if (result.success) {
          message.success('提交成功');
          props?.initDate();
        } else {
          message.error('提交失败');
        }

        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          name="fileName"
          label="文件名称"
          placeholder="请输入文件名称"
          rules={[
            {
              required: true,
              message: '请输入文件名称',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          width="sm"
          name="storageName"
          label="存储室"
          placeholder="请选择存储室"
          request={async () => {
            const list: any[] = [];
            const result = await request(api.getStorageList);

            result.data.forEach((item) => {
              list.push({ label: item.title, value: item.id });
            });

            return list;
          }}
          rules={[
            {
              required: true,
              message: '请选择存储室',
            },
          ]}
        />
        <ProFormSelect
          width="sm"
          name="userName"
          label="文件负责人"
          placeholder="请选择文件负责人"
          request={async () => {
            const list: any[] = [];
            const result = await request(api.getSimpleUserInfo);

            result.data.forEach((item) => {
              list.push({ label: item.name, value: item.id });
            });

            return list;
          }}
          rules={[
            {
              required: true,
              message: '请选择文件负责人',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea
          width="lg"
          name="fileDescribe"
          label="文件详细信息"
          tooltip="可以存储文件的地理信息、版本号等"
          placeholder="请输入文件详细信息"
          rules={[
            {
              required: true,
              message: '请输入文件详细信息',
            },
          ]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormUploadDragger
          max={1}
          width="lg"
          label="上传文件图览"
          name="fileOssPath"
          tooltip="该区域主要用于上传文件的样式图"
          description="仅支持单次上传"
          fieldProps={{
            beforeUpload: (file) => {
              SetFileInfo(file);
              return false;
            },
          }}
          rules={[
            {
              required: true,
              message: '请上传文件图览',
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

export default (props: propsType) => {
  const [state, setState] = useState<ProFieldFCMode>('read');
  const [plain, setPlain] = useState<boolean>(false);
  const [mouseDownTime, SetMouseDownTime] = useState<any>();
  const [fileInfo, SetFileInfo] = useState<fileType[]>();
  const [visible, SetVisible] = useState(false);
  const [moduleInfo, SetModuleInfo] = useState<moduleType>();
  const actionRef = useRef();
  const access = useAccess();
  const getDate = async () => {
    const result = await request(api.getStoreFileInfo, {
      method: 'POST',
      data: {
        ids: JSON.stringify(props.selectedRowKeys) ? JSON.stringify(props.selectedRowKeys) : '[]',
      },
    });

    SetFileInfo(result.data);
  };

  const initDate = async (id: string) => {
    const r = await request(api.getStoreFileById, {
      params: {
        id: id,
      },
    });

    SetModuleInfo(r.data);
  };

  const debounce = (foo: any, delay: any) => {
    let timer: any;
    return function () {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        foo.apply(this);
      }, delay);
    };
  };

  useEffect(() => {
    getDate();
  }, [props]);

  return (
    <ProCard
      wrap
      gutter={[5, 5]}
      title="文件列表"
      tooltip="鼠标左键短按查看，长按删除"
      extra={[
        <Access key={'insert'} accessible={access.normalButtonFilter('FILE_MEMORY:INSERT')}>
          <ModuleAddFileInfo initDate={getDate} key={'insert'} />
        </Access>,
      ]}
    >
      {fileInfo &&
        fileInfo.map((item) => {
          return (
            <ProCard
              key={item.id}
              colSpan={{ xs: 12, sm: 11, md: 10, lg: 8, xl: 6 }}
              layout="default"
              bordered
              hoverable
              ghost={true}
              onMouseDown={() => {
                SetMouseDownTime(new Date());
              }}
              onMouseUp={() => {
                const endTime = new Date();
                const b = access.normalButtonFilter('FILE_MEMORY:DELETE');
                if (endTime - mouseDownTime > 300 && b) {
                  Modal.warn({
                    title: '是否删除《 ' + item.fileName + ' 》文件',
                    okText: '确定',
                    maskClosable: true,
                    onOk: async () => {
                      const r = await request(api.deleteStoreFileById, {
                        params: {
                          id: item.id,
                        },
                      });

                      if (r.success) {
                        message.success('删除成功');
                        getDate();
                      } else {
                        message.warn('删除失败');
                      }
                    },
                  });
                } else if (access.normalButtonFilter('FILE_MEMORY:UPDATE')) {
                  SetVisible(true);
                  initDate(item.id);
                }
              }}
            >
              <div style={{ width: '100%', textAlign: 'center', marginTop: 10 }}>
                <Avatar
                  shape="square"
                  style={{ margin: ' auto' }}
                  src="https://sxit-gc.oss-cn-beijing.aliyuncs.com/tdf-bms-file/icon/%E6%96%87%E4%BB%B6%E8%A2%8B.png"
                />
              </div>
              <div style={{ fontSize: 10, marginTop: 10, textAlign: 'center', marginBottom: 10 }}>
                {item.fileName}
              </div>
            </ProCard>
          );
        })}

      <ModalForm
        title="文件信息"
        visible={visible}
        onFinish={() => {
          SetVisible(false);
        }}
        onVisibleChange={SetVisible}
      >
        <ProDescriptions<moduleType>
          actionRef={actionRef}
          bordered
          formProps={{
            onValuesChange: (e, f) => {
              const id = moduleInfo?.id;

              const deb = debounce(() => {
                request(api.updateStoreFileInfo, {
                  method: 'POST',
                  data: {
                    id: moduleInfo?.id,
                    ...e,
                  },
                }).then((item) => {
                  if (item.success) {
                    message.success('修改成功');
                    initDate(id);
                  } else {
                    message.success('修改失败');
                  }
                });
              }, 3000);

              deb();

              console.log(e);
            },
          }}
          dataSource={moduleInfo}
          editable={{}}
          column={2}
          columns={[
            {
              title: '文件标号',
              key: 'id',
              dataIndex: 'id',
              copyable: true,
              ellipsis: true,
              editable: false,
            },
            {
              title: '文件名称',
              key: 'fileName',
              dataIndex: 'fileName',
              valueType: 'text',
              ellipsis: true,
            },
            {
              title: '所属系部',
              key: 'deptName',
              dataIndex: 'deptName',
              valueType: 'text',
              editable: false,
            },
            {
              title: '文件责任人',
              key: 'userName',
              dataIndex: 'userName',
              valueType: 'select',
              request: async () => {
                const list: any[] = [];
                const result = await request(api.getSimpleUserInfo);

                result.data.forEach((item) => {
                  list.push({ label: item.name, value: item.id });
                });

                return list;
              },
            },
            {
              title: '文件创建时间',
              key: 'createTime',
              dataIndex: 'createTime',
              valueType: 'date',
              editable: false,
            },
            {
              title: '所属存储室',
              key: 'storageName',
              dataIndex: 'storageName',
              valueType: 'select',
              request: async () => {
                const list: any[] = [];
                const result = await request(api.getStorageList);

                result.data.forEach((item) => {
                  list.push({ label: item.title, value: item.id });
                });

                return list;
              },
            },
            {
              title: '文件详细表述',
              key: 'fileDescribe',
              dataIndex: 'fileDescribe',
              valueType: 'textarea',
            },
            {
              title: '文件图览',
              key: 'fileOssPath',
              dataIndex: 'fileOssPath',
              valueType: 'image',

              editable: false,
            },
          ]}
        />
      </ModalForm>
    </ProCard>
  );
};
